package com.bootdo.wx.controller;

import com.bootdo.common.config.BootdoConfig;
import com.bootdo.common.config.WxMaProperties;
import com.bootdo.common.utils.*;
import com.bootdo.wx.domain.*;
import com.bootdo.wx.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.math.BigDecimal;
import java.util.*;


/**
 * 商品
 * 
 * @author sys
 * @email 1992lcg@163.com
 * @date 2019-03-19 16:39:22
 */
 
@Controller
@RequestMapping("/wx/goodsGoods")
public class GoodsGoodsController {
	@Autowired
	private GoodsGoodsService goodsGoodsService;
	@Autowired
	private GoodsTypeService goodsTypeService;
	@Autowired
	private GoodsClassService goodsClassService;
	@Autowired
	private GoodsSpecService goodsSpecService;
	@Autowired
	private GoodsTypeParamgService goodsTypeParamgService;
	@Autowired
	private GoodsTypePropsService goodsTypePropsService;
	@Autowired
	private GoodsTypeBrandService goodsTypeBrandService;
	@Autowired
	private GoodsTypeSpecService goodsTypeSpecService;
	@Autowired
	private GoodsProductService goodsProductsService;
	@Autowired
	private GoodsImagesService goodsImagesService;
	@Autowired
	private GoodsBrandService goodsBrandService;
	@Autowired
	private GoodsTagService goodsTagService;
	@Autowired
	private BootdoConfig bootdoConfig;
	@Autowired
	private SetImageUploadService setImageUploadService;
	@Autowired
	private OrderComentService orderComentService;
	@Autowired
	private GoodsWarehouseService goodsWarehouseService;
	@Autowired
	private SalesCouponService salesCouponService;

	@Autowired
	private WxMaProperties properties;


	
	@GetMapping()
	@RequiresPermissions("wx:goodsGoods:goodsGoods")
	String GoodsGoods(){
	    return "wx/goodsGoods/goodsGoods";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("wx:goodsGoods:goodsGoods")
	public PageUtils list(@RequestParam Map<String, Object> params){

		List<Map<String,Object>> goodsGoodsList ;
		Query query = new Query(params);

		query.put("sort","gmt_create");
		query.put("order","desc");
		int total = 0;
		if(params.containsKey("name")&&StringUtils.isNotBlank(params.get("name").toString())){
			query.put("name", params.get("name").toString());
			goodsGoodsList = goodsGoodsService.getList(query);
			total=goodsGoodsService.countList(query);
		}else{
			 goodsGoodsList = goodsGoodsService.getList(query);
			 total = goodsGoodsService.count(query);
		}
		//查询列表数据
		PageUtils pageUtils = new PageUtils(goodsGoodsList, total);
		return pageUtils;
	}
	
	@GetMapping("/add")
	@RequiresPermissions("wx:goodsGoods:add")
	String add(Model model){
		Map<String,Object> map = new HashMap<String,Object>();
		model.addAttribute("typeList",goodsTypeService.queryAll());
		model.addAttribute("brandList",goodsBrandService.queryAll());
		//model.addAttribute("wareList",goodsWarehouseService.queryAll());
	    return "wx/goodsGoods/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("wx:goodsGoods:edit")
	String edit(@PathVariable("id") String id,Model model){
		//获取商品信息
		GoodsGoodsDO goodsGoods = goodsGoodsService.get(id);
	/*	Map<String, Object> par = new HashMap<>();
		par.put("goodsId", goodsGoods.getId());
		List<GoodsProductDO> list2 = goodsProductsService.list(par);
		for (GoodsProductDO goodsProductDO : list2) {
			if(goodsProductDO.get){
				
			}
		}*/
		//轮播图
		Map<String, Object> imgMap = new HashMap<>();
		imgMap.put("goodsId", id);
		imgMap.put("address", "0");
		imgMap.put("delFlag", "0");
		List<GoodsImagesDO> bannerList = goodsImagesService.list(imgMap);
		goodsGoods.setBanners(bannerList);
		//详情图
		imgMap.put("address", "1");
	    List<GoodsImagesDO> detailImgs = goodsImagesService.list(imgMap);
	    goodsGoods.setDetailImgs(detailImgs);
		
		String classId = goodsGoods.getClassId();
		GoodsClassDO goodsClassDO = goodsClassService.get(classId);
		if(goodsClassDO==null){
			Map<String,Object> map = new HashMap<>();
			map.put("level","1");
			map.put("show","0");
			map.put("del_flag","0");
			List<GoodsClassDO> goodsClassDOS = goodsClassService.list(map);
			model.addAttribute("goodsClass", goodsClassDOS.get(0));
		}else{
			model.addAttribute("goodsClass", goodsClassDO);
		}


		//获取商品类型对应的参数信息
		List<GoodsTypeParamgDO> typeParamgList = goodsTypeParamgService.queryListAndValueByTypeId(goodsGoods.getTypeId());
		//获取商品类型对应的规格信息
		List<GoodsTypeSpecDO> typeSpecList = goodsTypeSpecService.queryListAndValueByTypeId(goodsGoods.getTypeId());
		/*if(typeSpecList.size()<=0){
			Map<String, Object> par = new HashMap<>();
			par.put("goodsId", goodsGoods.getId());
			List<GoodsProductDO> list = goodsProductsService.list(par);
			if(list.size()>0){
			
					goodsGoods.setPriceF(list.get(0).getPriceF());
					goodsGoods.setPriceH(list.get(0).getPriceH());
					goodsGoods.setPriceL(list.get(0).getPriceL());
					goodsGoods.setPriceMarket(list.get(0).getPriceMarket());
					goodsGoods.setGoodsProduct(list.get(0));
				
			}
			
		}*/
		model.addAttribute("goodsGoods", goodsGoods);
		//组装商品各类关联表数据
//				shopGoodsService.fetchLinks(obj, null, Cnd.orderBy().asc("location"));
//				List<Goods_product> productsList = obj.getProductList();
		model.addAttribute("specList", typeSpecList);
		model.addAttribute("typeParamgList", typeParamgList);
		model.addAttribute("typeList", goodsTypeService.queryAll());
		model.addAttribute("brandList",goodsBrandService.queryAll());
		model.addAttribute("wareList",goodsWarehouseService.queryAll());
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("goodsId", goodsGoods.getId());
		map.put("delFlag","0");
		model.addAttribute("productNum", goodsProductsService.count(map));
		List<GoodsProductDO> list =goodsProductsService.list(map);
		if(list.size()>0){
			for (GoodsProductDO goodsProductDO : list) {
				if(goodsProductDO.getIsDefault()==1){
					goodsGoods.setGoodsProduct(goodsProductDO);
				}
			}
		}else{
			GoodsProductDO goodsProductDO = new GoodsProductDO();
			goodsProductDO.setPostFee(new BigDecimal("0.00"));
			goodsGoods.setGoodsProduct(goodsProductDO);
		}
		
		model.addAttribute("productList", list);
		//在页面上显示商品类型管理的品牌
		//model.addAttribute("brandList", goodsBrandService.listByTypeId(goodsGoods.getTypeId()));

	    return "wx/goodsGoods/edit";
	}
	//上架/下架页面
	@GetMapping("/resetShelf/{id}")
	@RequiresPermissions("wx:goodsGoods:edit")
	String resetShelf(@PathVariable("id") String id,Model model){
		//获取商品信息
		GoodsGoodsDO goodsGoods = goodsGoodsService.get(id);
		model.addAttribute("goodsGoods", goodsGoods);
		return "wx/goodsGoods/reset_shelf";
	}

	//修改团品页面
	/*@GetMapping("/resetGroup/{id}")
	@RequiresPermissions("wx:goodsGoods:edit")
	String resetGroup(@PathVariable("id") String id,Model model){
		//获取商品信息
		GoodsGoodsDO goodsGoods = goodsGoodsService.get(id);
		model.addAttribute("goodsGoods", goodsGoods);
		return "wx/goodsGoods/reset_group";
	}*/
	//修改推荐商品页面
	@GetMapping("/resetRecommend/{id}")
	@RequiresPermissions("wx:goodsGoods:edit")
	String resetRecommend(@PathVariable("id") String id,Model model){
		//获取商品信息
		GoodsGoodsDO goodsGoods = goodsGoodsService.get(id);
		model.addAttribute("goodsGoods", goodsGoods);
		//优惠券信息
		List<SalesCouponDO> couponS = salesCouponService.getCouponS();
		model.addAttribute("coupons", couponS);
		return "wx/goodsGoods/reset_recommend";
	}

	/**
	 * 修改推荐商品
	 *
	 * @param
	 * @return
	 */
	@ResponseBody
	@PostMapping("/updateRecommend")
	public R updateRecommend(GoodsGoodsDO goods) {
		goodsGoodsService.update(goods);
		return R.ok();
	}

	//修改秒杀商品页面
//	@GetMapping("/resetSpike/{id}")
//	@RequiresPermissions("wx:goodsGoods:edit")
//	String resetSpike(@PathVariable("id") String id,Model model){
//		//获取商品信息
//		GoodsGoodsDO goodsGoods = goodsGoodsService.get(id);
//		model.addAttribute("goodsGoods", goodsGoods);
//		return "wx/goodsGoods/reset_spike";
//	}

	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("wx:goodsGoods:add")
	public R save( GoodsGoodsDO goodsGoods, @RequestParam("products") String products,
				   @RequestParam("spec_values") String spec_values, //@RequestParam("prop_values") String prop_values,
				   @RequestParam("param_values") String param_values, @RequestParam("images") String images,
				   @RequestParam("imagesDetail") String imagesDetail){
		if(goodsGoods.getClassId()==null||"".equals(goodsGoods.getClassId())){
			return R.error("请选择分类");
		}
		//final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());

		//wxService.getShopSpuService().addSpu()


        return goodsGoodsService.add(goodsGoods, products, spec_values,  param_values, images ,imagesDetail);

	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("wx:goodsGoods:edit")
	public R update( GoodsGoodsDO goodsGoods, @RequestParam("products") String products,
					 @RequestParam("spec_values") String spec_values, //@RequestParam("prop_values") String prop_values,
					 @RequestParam("param_values") String param_values, @RequestParam("images") String images,
					 @RequestParam("imagesDetail") String imagesDetail){
		return goodsGoodsService.edit(goodsGoods, products, spec_values,  param_values, images ,imagesDetail);

	}
	
	/**
	 * 修改上下架
	 */
	@ResponseBody
	@RequestMapping("/updateShelf")
	@RequiresPermissions("wx:goodsGoods:edit")
	public R updateShelf( GoodsGoodsDO goodsGoods){
		if (goodsGoods.getDisabled()==0){
			goodsGoods.setUpAt(new Date());
		}else {
			goodsGoods.setDownAt(new Date());
		}
		if (goodsGoodsService.update(goodsGoods)>0){
			return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("wx:goodsGoods:remove")
	public R remove( String id){
		GoodsGoodsDO goodsGoodsDO = goodsGoodsService.get(id);
		goodsGoodsDO.setDelFlag(1);
		goodsGoodsDO.setGmtModified(new Date());
		if(goodsGoodsService.update(goodsGoodsDO)>0){
			return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("wx:goodsGoods:batchRemove")
	public R remove(@RequestParam("ids[]") String[] ids){
		for (String id : ids) {
			GoodsGoodsDO goodsGoodsDO = goodsGoodsService.get(id);
			goodsGoodsDO.setDelFlag(1);
			goodsGoodsDO.setGmtModified(new Date());
			goodsGoodsService.update(goodsGoodsDO);
		}
		return R.ok();
	}
	
	
	/**
	 * 根据ID查询商品类型详情
	 */
	@ResponseBody
	@PostMapping("/getType")
	public R getType(@RequestParam("id") String id){
		GoodsTypeDO goodsTypeDO = goodsTypeService.get(id);
		return R.ok().put("data", goodsTypeDO);
	}

	/**
	 * 通过商品类型获取品牌
	 *
	 * @param id
	 * @return
	 */
	@ResponseBody
	@PostMapping("/getBrand")
	public R getBrand(@RequestParam("id")String id) {
		List<GoodsTypeBrandDO> list = goodsTypeBrandService.queryAndBrandByTypeId(id);
//		shopGoodsTypeBrandService.fetchLinks(list, "brand", Cnd.orderBy().asc("location"));
		return R.ok().put("data", list);
	}

	/**
	 * 获取商品类型的扩展属性
	 *
	 * @param id
	 * @return
	 */
	@ResponseBody
	@PostMapping("/getProps")
	public R getProps(@RequestParam("id")String id) {
		List<GoodsTypePropsDO> list = goodsTypePropsService.queryListAndValueByTypeId(id);
//		shopGoodsTypeParamgService.fetchLinks(list, "params", Cnd.orderBy().asc("location"));
		return R.ok().put("data", list);
	}

	/**
	 * 获取商品类型的详细参数
	 *
	 * @param id
	 * @return
	 */
	@ResponseBody
	@PostMapping("/getParam")
	public R getParam(@RequestParam("id")String id) {
		List<GoodsTypeParamgDO> list = goodsTypeParamgService.queryListAndValueByTypeId(id);
//		shopGoodsTypeParamgService.fetchLinks(list, "params", Cnd.orderBy().asc("location"));
		return R.ok().put("data", list);
	}

	/**
	 * 获取商品分类及分类的商品类型
	 *
	 * @param id
	 * @return
	 */
	@ResponseBody
	@PostMapping("/getClass")
	public R getClass(@RequestParam("id")String id) {
//		List<GoodsClassDO> list = goodsClassService.queryAndTypeByTypeId(id);
		GoodsClassDO goodsClassDO = goodsClassService.get(id);
		if (goodsClassDO!=null){
			if(goodsClassDO.getLevel() != 1){
				return R.error("请选择二级分类!");
			}

			GoodsTypeDO type =goodsTypeService.get(goodsClassDO.getTypeId());
			goodsClassDO.setGoodsType(type);
		}

//		shopGoodsTypeParamgService.fetchLinks(list, "params", Cnd.orderBy().asc("location"));
		return R.ok().put("data", goodsClassDO);
	}


	/**
	 * 开启规格页面
	 *
	 * @param id
	 * @param sku
	 */
	@GetMapping("/spec")
	public String spec(String id, String sku,String stock,String priceMarket,String price,String rebateOne,String rebateTwo,
					   String postFee,String weight,String type, Model model,String priceC, String priceZ,String priceG) {

		List<GoodsTypeSpecDO> typeSpecList = goodsTypeSpecService.queryListAndValueByTypeId(id);

		if (StringUtils.isEmpty(sku.trim())) {
			sku = goodsProductsService.getSkuPrefix();
		}
		model.addAttribute("price", price);
		model.addAttribute("sku", sku.toUpperCase());
		model.addAttribute("postFee", postFee);
		model.addAttribute("priceMarket", priceMarket);
		model.addAttribute("rebateOne", rebateOne);
		model.addAttribute("rebateTwo", rebateTwo);
		model.addAttribute("weight", weight);
		model.addAttribute("specList", typeSpecList);
		model.addAttribute("type", type);
		model.addAttribute("stock", stock);
		model.addAttribute("priceC", priceC);
		model.addAttribute("priceZ", priceZ);
		model.addAttribute("priceG", priceG);

//		model.addAttribute();
//		req.setAttribute("specList", typeSpecList);
//		req.setAttribute("lvList", memberLevelService.query(Cnd.orderBy().asc("point")));
		return "wx/goodsGoods/spec";
	}




	@ResponseBody
	@PostMapping("/upload")
	R upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
		String fileName = null;
//		fileName = FileUtil.renameToUUID(fileName);
//		GoodsImagesDO goodsImagesDO = new GoodsImagesDO("", "/files/" + fileName,0, new Date());
		try {
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image != null) {//如果image=null 表示上传的不是图片格式
//			    System.out.println(image.getWidth());//获取图片宽度，单位px
//			    System.out.println(image.getHeight());//获取图片高度，单位px
                fileName = "IMG_" + image.getWidth() + "_" + image.getHeight() + "@"+ UUID.randomUUID().toString();;
            }else {
                fileName = UUID.randomUUID().toString();
            }
//			FileUtil.uploadFile(file.getBytes(), bootdoConfig.getUploadPath(), fileName);
			String imagePath = new ImgUpload(setImageUploadService).upload(file.getBytes(),
					fileName);
			return R.ok().put("data", imagePath);
		} catch (Exception e) {
			return R.error();
		}

	}
	/**
	 * 所有商品ID和名字
	 *
	 * @param
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getGoods")
	public R getGoods() {
		List<Map<String,Object>> list = goodsGoodsService.queryAllForIdAndName(new HashMap<String,Object>());
//		shopGoodsTypeParamgService.fetchLinks(list, "params", Cnd.orderBy().asc("location"));
		return R.ok().put("data", list);
	}

	/*查看商品评论*/
	@GetMapping("/getComent/{id}")
	String getComent(@PathVariable("id") String id,Model model){
		model.addAttribute("goodsId", id);
		return "wx/goodsGoods/coment";
	}

	/**
	 * 获取商品评论列表
	 */
	@ResponseBody
	@RequestMapping("/getComentList")
	public PageUtils getComentList(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<Map<String,Object>> comentList = orderComentService.getComentList(query);
		int total = orderComentService.getComentListCount(query);
		PageUtils pageUtils = new PageUtils(comentList, total);
		return pageUtils;
	}
}
